<template>
  <div class="login">
    <el-form
      ref="loginForm"
      :model="loginForm"
      :rules="loginRules"
      class="login-form"
    >
      <h3 class="title">{{settings.title}}</h3>
      <el-form-item prop="username">
        <el-input
          v-model="loginForm.username"
          type="text"
          auto-complete="off"
          placeholder="账号"
        >
          <svg-icon
            slot="prefix"
            icon-class="user"
            class="el-input__icon input-icon"
          />
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model="loginForm.password"
          type="password"
          auto-complete="off"
          placeholder="密码"
          @keyup.enter.native="handleLogin"
        >
          <svg-icon
            slot="prefix"
            icon-class="password"
            class="el-input__icon input-icon"
          />
        </el-input>
      </el-form-item>
      <el-form-item prop="code" v-if="captchaType === 'default'">
        <el-input
          v-model="loginForm.code"
          auto-complete="off"
          placeholder="验证码"
          style="width: 63%"
          @keyup.enter.native="handleLogin"
        >
          <svg-icon
            slot="prefix"
            icon-class="validCode"
            class="el-input__icon input-icon"
          />
        </el-input>
        <div class="login-code">
          <img
            :src="codeUrl"
            @click="getCode"
            width="100px"
            height="38px"
            class="login-code-img"
          />
        </div>
      </el-form-item>

      <el-form-item prop="puzzleComplete" v-if="captchaType === 'puzzle'">
        <qm-puzzle-code
          v-model="loginForm.puzzleComplete"
          @success="puzzleSuccess"
        />
      </el-form-item>

      <!-- <el-checkbox v-model="loginForm.rememberMe" style="margin:0px 0px 25px 0px;">记住密码</el-checkbox> -->
      <el-form-item style="width: 100%">
        <el-button
          :loading="loading"
          size="medium"
          type="primary"
          style="width: 100%"
          @click.native.prevent="handleLogin"
        >
          <span v-if="!loading">登 录</span>
          <span v-else>登 录 中...</span>
        </el-button>
      </el-form-item>
    </el-form>
    <!--  底部  -->
    <div class="el-login-footer">
      <span v-if="settings.copyright">{{settings.copyright}}</span>&nbsp;&nbsp;
      <a target="_blank" href="https://beian.miit.gov.cn" v-if="settings.icp">{{settings.icp}}</a>&nbsp;&nbsp;
      <a target="_blank" :href="settings.supportUrl" v-if="settings.support">技术支持：{{settings.support}}</a>
    </div>
  </div>
</template>

<script>
import { encrypt, decrypt } from "@/utils/jsencrypt";
import JSEncrypt from "jsencrypt/bin/jsencrypt.min";
import { Message } from "element-ui";
import request from "@/utils/request";
import _ from "lodash";
import QmPuzzleCode from "@/libs/components/qm-puzzle-code/index.vue";
import Settings from "../settings";

export default {
  name: "Login",
  components: {
    QmPuzzleCode
  },
  data() {
    const validatorPuzzleComplete = (rule, value, callback) => {
      if (value) {
        if (!this.loginForm.activationCode || !this.loginForm.activationTime) {
          return callback(new Error("请完成图片验证"));
        } else {
          callback();
        }
      } else {
        return callback(new Error("请完成图片验证"));
      }
    };
    return {
      settings: Settings,
      codeUrl: "",
      cookiePassword: "",
      isShow: true,
      loginForm: {
        username: "",
        password: "",
        rememberMe: false,
        code: "",
        uuid: "",
        puzzleComplete: false,
        activationCode: "",
        activationTime: ""
      },
      loginRules: {
        username: [
          { required: true, trigger: "blur", message: "用户名不能为空" }
        ],
        password: [
          { required: true, trigger: "blur", message: "密码不能为空" }
        ],
        code: [
          { required: true, trigger: "change", message: "验证码不能为空" }
        ],
        puzzleComplete: [
          {
            required: true,
            validator: validatorPuzzleComplete,
            trigger: "change"
          }
        ]
      },
      loading: false,
      redirect: undefined,
      rsaPublic: ""
    };
  },
  computed: {
    captchaType() {
      return this.$store.state.settings.captchaType;
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true
    }
  },
  created() {
    this.getRsaPublic().then(r => {
      // this.getCookie();
    });
    this.getCode();
  },
  methods: {
    getRsaPublic() {
      return new Promise((rs, rj) => {
        request.post("/getRsaPublic").then(r => {
          if (r && r.parameters && r.parameters.rsaPublic) {
            this.rsaPublic = r.parameters.rsaPublic;
            rs();
          } else {
            this.notifyError("获取数据失败");
            rj();
          }
        });
      });
    },
    getCode() {
      this.codeUrl = `${
        process.env.VUE_APP_BASE_API
      }/login/getVerifyCode?_r=${Math.random()}`;
    },
    getCookie() {
      // 公钥加密，私钥解密，私钥不应该存储在客户端，记住密码功能不做
      // let encryptor = new JSEncrypt();
      // encryptor.setPublicKey(this.rsaPublic);
      // const username = localStorage.getItem("username");
      // const password = localStorage.getItem("password");
      // const rememberMe = localStorage.getItem("rememberMe");
      // this.loginForm = {
      //   username: username === undefined ? this.loginForm.username : username,
      //   password:
      //     password === undefined
      //       ? this.loginForm.password
      //       : encryptor.decrypt(password),
      //   rememberMe: rememberMe === undefined ? false : Boolean(rememberMe),
      // };
    },
    puzzleSuccess(event) {
      this.$nextTick(() => {
        this.loginForm.puzzleComplete = true;
        this.loginForm.activationCode = event.activationCode;
        this.loginForm.activationTime = event.activationTime;
        this.$refs["loginForm"].clearValidate("puzzleComplete");
      });
    },
    handleLogin() {
      if (!this.rsaPublic) {
        this.notifyError("无法完成操作，请刷新页面重试");
        return;
      }
      let encryptor = new JSEncrypt();
      encryptor.setPublicKey(this.rsaPublic);

      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true;
          let postModel = _.extend({}, this.loginForm);
          if (postModel.rememberMe) {
            localStorage.setItem("username", postModel.username, { expires: 30 });
            localStorage.setItem("password", encryptor.encrypt(postModel.password), {
              expires: 30
            });
            localStorage.setItem("rememberMe", postModel.rememberMe, {
              expires: 30
            });
          } else {
            localStorage.removeItem("username");
            localStorage.removeItem("password");
            localStorage.removeItem("rememberMe");
          }

          postModel.encryptor = encryptor;
          this.$store
            .dispatch("Login", postModel)
            .then(() => {
              this.$router.push({ path: this.redirect || "/" }).catch(() => {});
            })
            .catch(error => {
              this.loading = false;
              this.$refs["loginForm"].clearValidate();
              if (this.captchaType === "default") {
                this.getCode();
              } else if (this.captchaType === "puzzle") {
                this.loginForm.puzzleComplete = false;
              }
              Message({
                message: error,
                type: "error"
              });
            });
        }
      });
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss">
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-image: url("../assets/images/login-background.jpg");
  background-size: cover;
}
.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #707070;
}

.login-form {
  border-radius: 6px;
  background: #ffffff;
  width: 400px;
  padding: 25px 25px 5px 25px;
  .el-input {
    height: 38px;
    input {
      height: 38px;
    }
    .el-input__inner {
      padding-left: 30px !important;
    }
  }
  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }
}
.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}
.login-code {
  width: 33%;
  height: 38px;
  float: right;
  img {
    cursor: pointer;
    vertical-align: middle;
  }
}
.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-size: 12px;
  letter-spacing: 1px;
}
.login-code-img {
  // height: 38px;
}
</style>
